<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="900" :close-on-click-modal="false" center>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px" class="attraction-form">
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入标题" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="坐标位置" prop="position">
              <el-input v-model="formData.position" placeholder="请选择坐标位置" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="查岗时间" prop="workDate">
              <el-date-picker type="datetime" v-model="formData.workDate" placeholder="请选择查岗时间" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入详细地址" clearable>
            <template #append>
              <el-button :icon="Location" @click="handleShowPosition" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="100">进行中</el-radio>
            <el-radio :value="200" label="200">已结束</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <!-- 描述信息 -->
      <div class="form-section">
        <h3 class="section-title">描述信息</h3>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="4" placeholder="请输入详细描述，包括人数、历史背景等" maxlength="500" show-word-limit />
        </el-form-item>
      </div>

      <!-- 图片管理 -->
      <div class="form-section">
        <h3 class="section-title">图片管理</h3>
        <el-form-item label="图片">
          <div class="image-upload-container">
            <el-upload v-model:file-list="fileList" action="#" list-type="picture-card" :auto-upload="false" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforeUpload" multiple>
              <el-icon><Plus /></el-icon>
            </el-upload>
          </div>
        </el-form-item>
        <div class="upload-tip">
          <el-text size="small" type="info"> 支持 jpg、png、gif 格式，单张图片不超过 2MB，最多上传 5 张 </el-text>
        </div>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" size="large" @click="submitForm" :loading="submitting"> {{ editMode ? '保存' : '发布' }} </el-button>
        <el-button size="large" @click="() => (dialogVisible = false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
  <LocationView ref="refLocationView" @change="handlePositionChange" />
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import { Plus, Location } from '@element-plus/icons-vue'
import http from '@/apis/traffic'
import type { FormInstance, FormRules, UploadUserFile, UploadProps } from 'element-plus'
import { useUserStore } from '@/stores/user'
import LocationView from '@/components/location.vue'

const refLocationView = ref<typeof LocationView>()

const handleShowPosition = () => {
  // console.log(formData.value.position)
  refLocationView.value?.handleShow(formData.value.position)
}

interface positionType {
  location: string
  lat: number
  lng: number
}

const handlePositionChange = (obj: positionType) => {
  // console.log(obj)
  formData.value.position = obj.location
}

const dialogTitle = ref('新增数据')
const userStore = useUserStore()
const submitting = ref(false)
const user = computed(() => userStore.userInfo)

// 响应式数据
const formRef = ref<FormInstance>()
const inputRef = ref()
const dialogVisible = ref(false)
const dialogImageUrl = ref('')
const inputVisible = ref(false)
const inputValue = ref('')
const fileList = ref<UploadUserFile[]>([])

// 表单数据
const formData = ref({
  title: '', // 标题
  workDate: '', // 查岗时间
  address: '', // 详细地址
  position: '', // 坐标位置
  description: '', // 描述
  status: 100, // 状态，100 进行中 200 已结束
  tagsJson: ['查酒驾'], // 标签
  imageUrls: []
})

// 表单验证规则
const rules: FormRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 3, max: 100, message: '地址长度在 3 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入景点描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

const removeTag = (tag: string) => {
  const index = formData.value.tagsJson.indexOf(tag)
  if (index > -1) {
    formData.value.tagsJson.splice(index, 1)
  }
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value && !formData.value.tagsJson.includes(inputValue.value)) {
    formData.value.tagsJson.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

const addPresetTag = (tag: string) => {
  if (!formData.value.tagsJson.includes(tag)) {
    formData.value.tagsJson.push(tag)
  }
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png', 'image/gif'].includes(rawFile.type)) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 构造提交数据
    let submitData = {
      ...formData.value,
      tagsJson: '',
      imageUrls: ''
    }
    submitData.tagsJson = JSON.stringify(formData.value.tagsJson)
    submitData.imageUrls = JSON.stringify(formData.value.imageUrls)
    if (editMode.value) {
      submitUpdate(submitData)
    } else {
      submitCreate(submitData)
    }
  } catch (error) {
    ElMessage.error('请检查表单填写是否完整')
  } finally {
    submitting.value = false
  }
}

const submitCreate = (submitData: any) => {
  // API调用
  http
    .create(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('发布成功！')
      dialogVisible.value = false
      emit('create', submitData)
    })
    .catch(() => {
      ElMessage.error('发布失败，请稍后重试')
    })
}
const submitUpdate = (submitData: any) => {
  let keys = ['updateTime', 'updateUserId', 'updateUserName', 'userId']
  keys.forEach((t) => delete submitData[t])
  submitData.status = submitData.status ?? 100
  http
    .update(submitData)
    .then((response) => {
      let { code, message } = response.data
      if (code != 200) {
        ElMessage.error(message)
        return
      }
      ElMessage.success('更新成功！')
      dialogVisible.value = false
      emit('update', submitData)
    })
    .catch(() => {
      ElMessage.error('更新失败，请稍后重试')
    })
}
// 重置表单
const resetForm = () => {
  ElMessageBox.confirm('确定要重置表单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formRef.value?.resetFields()
    formData.value.tagsJson = []
    formData.value.imageUrls = []
    ElMessage.success('表单已重置')
  })
}
const emit = defineEmits(['update', 'create'])
const editMode = ref(false)

const handleCreate = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增数据'
  editMode.value = false
  formData.value = {
    title: '', // 标题
    workDate: dayjs(new Date()).format('YYYY-MM-DD HH:mm'), // 查岗时间
    address: '东川区', // 详细地址
    position: '', // 坐标位置
    description: '', // 描述
    status: 100, // 状态，100 进行中 200 已结束
    tagsJson: ['查酒驾'], // 标签
    imageUrls: []
  }
}
const handleModify = (obj: any) => {
  dialogVisible.value = true
  formData.value = { ...obj }
  editMode.value = true
  dialogTitle.value = '编辑数据'
  formData.value.tagsJson = JSON.parse(obj.tagsJson)
  formData.value.imageUrls = JSON.parse(obj.imageUrls)
  //   console.log(obj)
}

defineExpose({
  handleCreate,
  handleModify
})
</script>
<style>
.form-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.job-form {
  display: flex;
  flex-wrap: wrap;
}

.form-section {
  margin: 10px 10px;
  flex: 1 1;
  min-width: 400px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-child {
  border-bottom: none;
}

.section-title {
  margin: 0 0 20px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  margin-bottom: 12px;
}

.tags-input {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  margin: 0;
}

.tag-input {
  width: 120px;
}

.preset-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.submit-section {
  padding: 20px 0px;
  display: flex;
  justify-content: center;
}

.submit-section .el-button {
  margin: 0 8px;
  min-width: 120px;
}

/* 预览样式 */
.job-preview {
  padding: 16px;
}

.preview-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-avatar {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
  margin-right: 16px;
}

.preview-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
}

.preview-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.preview-details {
  margin-top: 16px;
}

.preview-tags {
  margin-top: 16px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>
